import log from './logger'
import config from "./config";
import * as mssql from "mssql";
import {axios} from "../node-test";

class MengdongMssqlCollector {
    init() {
        this.collection();
        setInterval(() => {
            this.collection();
        }, 1000 * 60)
    }

    async query(path: "trains" | "firstNodes" | "secondNodes", sql: string) {
        try {
            // todo 需要本地比对数据，只上传不同记录？
            const res = await new mssql.Request().query(sql);
            return res.recordset
        } catch (e) {
            log.error(e);
        }
    }

    async collection() {
        const cfg = {
            user: "hlsk",
            password: "hlsk",
            server: "192.168.0.15",
            database: "WY_DATAMANAGE",
            port: 1433,
            options: {
                encrypt: false,
                tdsVersion: '7_1'
            }
        };
        await mssql.connect(cfg);
        try {
            let train_sql = "SELECT \n    top 10 \n    t.LISTID as code,\n    CONVERT(varchar(100), t.LISTTIME, 120) as time,\n    t.NODECOUNT as totalNode, \n\tcase when direction = '右' then '进' else '出' end as direction\nFROM \n    TB_LIST_INFORMATION t \nORDER BY \n    t.LISTID desc"
            let recordset = await this.query("trains", train_sql)
            const trainsData = {
                platformId: config.platformId,
                platformName: config.platformName,
                data: JSON.parse(JSON.stringify(recordset))
            }
            log.info(trainsData)
            const url = "https://platform.ncexc-rm.com/api/depatch/internal/unloadTrain/trains"
            axios.post(url, trainsData).then((res: any) => {
                // log.info("send ok")
                if (res.data.code === '0000') {
                    // resolve("ok");
                } else {
                    log.error("send err data:", "trains", trainsData)
                    log.error("send err:", res.data.code, res.data.data)
                }
            }).catch((e) => {
                log.error("send err:", e.message)
            })
            // 获取trainCode list
            for (let recordsetElement of recordset) {
                let code = recordsetElement.code;
                let train_node_first_sql = "SELECT n.LISTID as trainCode,\n\tn.NODEID as code,\n\tn.WEIGHT as weight,\n\tn.SPEED as speed,\n\tCONVERT(varchar(100), n.NODETIME, 120) as time,\n\tn.VEHICLETYPE as type,\n\tn.VEHICLEID as no,\n\tsw.STANDARDWEIGHT as standardTareWeight,\n\tsw.maxweight as maxNetWeight\nFROM \n\tTB_ONCEWEIGHING n \nleft join \n\tTB_STANDARDWEIGHT sw on sw.vehicletype = n.VEHICLETYPE\nwhere\n\tn.LISTID = '${trainCode}' order by n.code"
                let firstRecordset = await this.query("firstNodes", train_node_first_sql.replace('${trainCode}', code));
                // 发送一次数据
                const firstData = {
                    platformId: config.platformId,
                    platformName: config.platformName,
                    data: JSON.parse(JSON.stringify(firstRecordset))
                }
                log.info(firstData)
                const url = "https://platform.ncexc-rm.com/api/depatch/internal/unloadTrain/firstNodes"
                axios.post(url, firstData).then((res: any) => {
                    // log.info("send ok")
                    if (res.data.code === '0000') {
                        // resolve("ok");
                    } else {
                        log.error("send err data:", "firstNodes", firstData)
                        log.error("send err:", res.data.code, res.data.data)
                    }
                }).catch((e) => {
                    log.error("send err:", e.message)
                })
                // let secondRecordset = await this.query("secondNodes", config.mssql.train_node_second_sql.replace('${trainCode}', code));
                // // 发送二次数据
                // const secondData = {
                //     platformId: config.platformId,
                //     platformName: config.platformName,
                //     type: recordsetElement.type,
                //     data: JSON.parse(JSON.stringify(secondRecordset))
                // }
                // log.info(secondData)
                // await sender.send("secondNodes", secondData);
            }
        } catch (e) {
            log.error(e);
        }
    }
}

const mengdongMssqlCollector = new MengdongMssqlCollector();
export default mengdongMssqlCollector;